package com.stockz.ui.swing.charting.util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.stockz.core.model.Bar;
import com.stockz.core.model.Scrip;
import com.stockz.core.util.BarUtil;
import com.stockz.core.util.Global;
import com.stockz.downloaderx.Download;
import com.stockz.downloaderx.Downloader.Callback;
import com.stockz.downloaderx.yahoo.YahooDownloader;
import com.stockz.ui.swing.charting.view.StockChartPanel;

@Component
public class DataUtil {
	
	@Autowired
	private YahooDownloader yahooDownloader;

	public void downloadLatestBar(){
		Calendar calendar = Calendar.getInstance();
		/*if(Calendar.SUNDAY == calendar.get(Calendar.DAY_OF_WEEK)
				|| Calendar.SATURDAY == calendar.get(Calendar.DAY_OF_WEEK)
				|| calendar.get(Calendar.HOUR_OF_DAY) < 9
				|| calendar.get(Calendar.HOUR_OF_DAY) > 15){
			return;
		}*/
		StockChartPanel panel = (StockChartPanel)Global.get(UIChartingConstant.SelectedStockChartPanel);
		if(panel != null){
			Scrip scrip = panel.getStockChartPanelState().getScrip();
			if(scrip != null && StringUtils.hasText(scrip.getCode())){
				List<Callback> callbackList = new ArrayList<Callback>();
				callbackList.add(new UpdateUICallback());
				yahooDownloader.download(scrip, calendar.getTime(), calendar.getTime(), callbackList);
			}
		}
	}
}



class UpdateUICallback implements Callback{
	@SuppressWarnings("deprecation")
	@Override
	public void execute(Download download) {
		if(download.getEvent().equals(EVENT.PARSE)
				&& download.getType().equals(TYPE.SUCCESS)){
			StockChartPanel panel = (StockChartPanel)Global.get(UIChartingConstant.SelectedStockChartPanel);
			if(panel != null){
				List<Bar> barList = panel.getStockChartPanelState().getBarList();
				if(barList != null && !barList.isEmpty()
						&& download.getBarList() != null
						&& !download.getBarList().isEmpty()){
					Bar bar = barList.get(0);
					Bar latest = download.getBarList().get(0);
					if(bar.getDate().getDate() < latest.getDate().getDate()){
						Bar newBar = new Bar();
						BarUtil.copy(bar, newBar);
						BarUtil.copy(latest, newBar);
						barList.add(0,newBar);
						RepaintStockChartPanelUtil.repaintStockChartPanel(panel);
					}else{
						if(bar.getHigh() != latest.getHigh()
								|| bar.getLow() != latest.getLow()
								|| bar.getClose() != latest.getClose()
								|| bar.getVolume() != latest.getVolume()){
							BarUtil.copy(latest, bar);
							RepaintStockChartPanelUtil.repaintStockChartPanel(panel);
						}
					}
				}
			}
		}
	}
	
	@Override
	public int getOrder() {
		return 0;
	}
}
